package me.jessyan.armscomponent.app.mvp.presenter.user;

import android.app.Application;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.armscomponent.app.mvp.contract.user.UserRetrievePasswordContract;
import me.jessyan.armscomponent.app.mvp.model.entity.RetrievePasswordRequest;
import me.jessyan.armscomponent.commonsdk.core.AccountDataProvider;
import me.jessyan.armscomponent.commonsdk.core.ResultCodeHub;
import me.jessyan.armscomponent.commonsdk.core.User;
import me.jessyan.armscomponent.commonsdk.http.BaseResponse;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


/**
 * <p>
 * Author: Taozebi
 * Date: 08/08/2021 15:36
 * Description: describe of this class
 */
@ActivityScope
public class UserRetrievePasswordPresenter extends BasePresenter<UserRetrievePasswordContract.Model, UserRetrievePasswordContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public UserRetrievePasswordPresenter(UserRetrievePasswordContract.Model model, UserRetrievePasswordContract.View rootView) {
        super(model, rootView);
    }

    public void login(){
        String username = mRootView.getUserName();
        String password = mRootView.getPassword();
        String passwordComfirm = mRootView.getPasswordComfirm();
        String ver_code = mRootView.getSmsCaptcha();
        if(TextUtils.isEmpty(username)){
            mRootView.showMessage("请输入手机号");
            return;
        }
        if(TextUtils.isEmpty(password)){
            mRootView.showMessage("请输入密码");
            return;
        }
        if(TextUtils.isEmpty(passwordComfirm)){
            mRootView.showMessage("请输入确认密码");
            return;
        }
        if(TextUtils.isEmpty(ver_code)){
            mRootView.showMessage("请输入验证码");
            return;
        }

        if(!mRootView.comfirmPassword()){
            mRootView.showMessage("两次密码输入不一致");
            return;
        }
        RetrievePasswordRequest loginRequest = new RetrievePasswordRequest();
        loginRequest.setMobile(username);
        loginRequest.setPassword(password);
        loginRequest.setVerifyCode(ver_code);
        mModel.forgetLoginPwd(loginRequest)
                .subscribeOn(Schedulers.io())
//                .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();//隐藏下拉刷新的进度条
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse<Object>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse<Object> userBaseResponse) {
                        if(userBaseResponse.success()){
                            mRootView.onRetrievePasswordSuccess();
                        }else {
                            BaseResponse.Errmsg errmsg = userBaseResponse.getErrmsg();
                            if(null != errmsg){
                                mRootView.showMessage(errmsg.getEn());
                            }else{
                                mRootView.showMessage("接口返回参数异常");
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable t) {
                        super.onError(t);
                        mRootView.showMessage("接口调用异常,"+t.getMessage());
                    }
                });
    }

    public void cacheUser(User user){
        AccountDataProvider.getInstance(mApplication.getApplicationContext()).cacheUser(user);
    }

    public void smsCaptcha(String mobile){
        startCount(60);
        mModel.smsCaptcha(mobile)
                .subscribeOn(Schedulers.io())
//                .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();//显示下拉刷新的进度条
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();//隐藏下拉刷新的进度条
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse<Object>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse<Object> datas) {
                        if(datas != null){
                            if (datas.success()) {
                            } else {
                                BaseResponse.Errmsg errmsg = datas.getErrmsg();
                                if(null != errmsg){
                                    mRootView.showMessage(errmsg.getEn());
                                }else{
                                    mRootView.showMessage("接口返回参数异常");
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable t) {
                        super.onError(t);
                        mRootView.showMessage("接口异常,"+t.getMessage());
                        mRootView.getVerCodeUnable(true,"获取验证码");
                    }
                });
    }


    private void startCount(final int times) {

        Observable.interval(0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<Long, Object>() {
                    @Override
                    public Object apply(@NonNull Long aLong) throws Exception {
                        //将1 2 3 4 5 6 转换成 6 5 4 3 2 1
                        return times - aLong.intValue();
                    }
                })
                .take(times + 1) //过滤掉times+1后面的数字
                .subscribe(new ErrorHandleSubscriber<Object>(mErrorHandler) {

                               @Override
                               public void onNext(@NonNull Object obj) {
                                   mRootView.getVerCodeUnable(false, obj.toString()+"s重新获取");
                               }

                               @Override
                               public void onComplete() {
                                   super.onComplete();
                                   mRootView.getVerCodeUnable(true, "获取验证码");
                               }
                           }
                );

    }



    public void checkMobile(){
        String mobile = mRootView.getUserName();
        if(TextUtils.isEmpty(mobile)){
            mRootView.showMessage("请输入手机号码");
            return;
        }

//        if(!StringUtil.isNumeric(mobile)){
//            mRootView.showMessage("手机号码必须是数字");
//            return;
//        }
//
//        if(mobile.length() != 11){
//            mRootView.showMessage("手机号码必须是11数字");
//            return;
//        }
        mModel.checkMobile(mobile)
                .subscribeOn(Schedulers.io())
//                .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();//显示下拉刷新的进度条
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();//隐藏下拉刷新的进度条
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse<Object>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse<Object> datas) {
                        if(datas != null){
                            if (datas.success()) {
//                                mRootView.toNext();
                                mRootView.showMessage("手机号不存在");
                            } else {
                                String code = datas.getCode();
                                if(ResultCodeHub.CODE_E2000.equals(code)){
                                    smsCaptcha(mobile);
                                }else{
                                    BaseResponse.Errmsg errmsg = datas.getErrmsg();
                                    if(null != errmsg){
                                        mRootView.showMessage(errmsg.getEn());
                                    }else{
                                        mRootView.showMessage("接口返回参数异常");
                                    }
                                }

                            }
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable t) {
                        super.onError(t);
                        mRootView.showMessage("接口异常,"+t.getMessage());
                    }
                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    //保存图片到SD卡
    public void saveFile(Bitmap bm, String fileName) throws IOException {

        String imgName = UUID.randomUUID().toString() + ".jpg"; //随机生成不同的名字
        File jia = new File(fileName);              //新创的文件夹的名字
        if (!jia.exists()) {   //判断文件夹是否存在，不存在则创建
            jia.mkdirs();
        }
        File file = new File(jia + "/" + imgName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);

        bos.flush();
        bos.close();

    }

}
